package blockchain

import (
	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
	"github.com/hyperledger/fabric-sdk-go/pkg/core/config"
	"github.com/hyperledger/fabric-sdk-go/pkg/fabsdk"
)

var (
	SDK           *fabsdk.FabricSDK
	channelName   = "mychannel"
	chaincodeName = "mychaincode"
	User          = "Admin"
	Org           = "Org1"
	configPath    = "/home/szc/go/src/example/application/config_e2e.yaml"
)

func Init() {
	var err error
	SDK, err = fabsdk.New(config.FromFile(configPath))
	if err != nil {
		panic(err.Error())
	}
}

func ChannelQuery(fnc string, args [][]byte) (channel.Response, error) {
	context := SDK.ChannelContext(channelName, fabsdk.WithOrg(Org), fabsdk.WithUser(User))

	cli, err := channel.New(context)
	if err != nil {
		return channel.Response{}, err
	}

	resp, err := cli.Query(channel.Request{
		Fcn:         fnc,
		ChaincodeID: chaincodeName,
		Args:        args,
	}, channel.WithTargetEndpoints("peer0.org1.example.com", "peer0.org2.example.com"))
	if err != nil {
		return channel.Response{}, err
	}

	return resp, nil
}

func ChannelExecute(fnc string, args [][]byte) (channel.Response, error) {
	context := SDK.ChannelContext(channelName, fabsdk.WithOrg(Org), fabsdk.WithUser(User))
	cli, err := channel.New(context)
	if err != nil {
		return channel.Response{}, err
	}
	resp, err := cli.Execute(channel.Request{
		Fcn:         fnc,
		ChaincodeID: chaincodeName,
		Args:        args,
	}, channel.WithTargetEndpoints("peer0.org1.example.com", "peer0.org2.example.com"))
	if err != nil {
		return channel.Response{}, err
	}
	return resp, nil
}
